package utils

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 标准响应码
// 定义状态码常量
const (
	// HTTP标准状态码
	SuccessCode    = http.StatusOK         // 200 成功状态码
	CreatedCode    = http.StatusCreated    // 201 已创建
	BadRequestCode = http.StatusBadRequest // 400 请求错误
	// 自定义状态码
	SUCCESS = SuccessCode // 成功状态码
	FAIL    = 500         // 失败状态码
)

// R 响应信息主体
type R[T any] struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data T      `json:"data"`
}

// OkWithData 返回带数据的成功响应
func OkWithData[T any](data T) *R[T] {
	return restResult(data, SUCCESS, "操作成功")
}

// OkNoData 返回不带数据的成功响应
func OkNoData[T any]() *R[T] {
	return restResult(*new(T), SUCCESS, "操作成功")
}

// 或者带自定义消息的版本
func OkNoDataWithMessage[T any](msg string) *R[T] {
	return restResult(*new(T), SUCCESS, msg)
}

// FailWithMsg 返回失败响应
func FailWithMsg[T any](msg string) *R[T] {
	return restResult(*new(T), FAIL, msg)
}

// FailWithCodeAndMsg 返回指定状态码和消息的失败响应
func FailWithCodeAndMsg[T any](msg string) *R[T] {
	return restResult(*new(T), 500, msg)
}

func FailWithMessage[T any](msg string) *R[T] {
	return FailWithMsg[T](msg)
}

// restResult 构造响应结果的私有方法
func restResult[T any](data T, code int, msg string) *R[T] {
	return &R[T]{
		Code: code,
		Msg:  msg,
		Data: data,
	}
}

// jsonResponse 统一处理JSON响应
func jsonResponse(c *gin.Context, response interface{}) {
	c.JSON(http.StatusOK, response)
}

// writeJSONResponse 带状态码的JSON响应
func writeJSONResponse(c *gin.Context, statusCode int, response interface{}) {
	c.JSON(statusCode, response)
}

// OkResponse 返回200成功响应
func OkResponse[T any](c *gin.Context, data T) {
	c.JSON(http.StatusOK, OkWithData(data))
}

func OkResponseNoData[T any](c *gin.Context) {
	c.JSON(http.StatusOK, OkNoData[T]())

}
func OkResponseNoDataWithMessage[T any](c *gin.Context, msg string) {
	c.JSON(http.StatusOK, OkNoDataWithMessage[T](msg))
}

// FailResponse 通用失败响应
func FailResponse[T any](c *gin.Context, msg string) {
	c.JSON(http.StatusOK, FailWithCodeAndMsg[T](msg))
}

// CreatedResponse 返回201创建成功响应
func CreatedResponse[T any](c *gin.Context, data T) {
	c.JSON(http.StatusCreated, OkWithData(data))
}

// BadRequestResponse 返回400请求错误响应
func BadRequestResponse[T any](c *gin.Context, msg string) {
	c.JSON(http.StatusBadRequest, FailWithMsg[T](msg))
}

// ErrorResponse 返回500服务器错误响应
func ErrorResponse[T any](c *gin.Context, msg string) {
	c.JSON(http.StatusInternalServerError, FailWithMsg[T](msg))
}

// FailWithMessage FailWithMsg的别名
